﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Com.Lancetinc.Evs.Reports.RadPdf;

internal class FrameworkElementRenderer : UIElementRendererBase
{
    private readonly Type[] types;

    internal FrameworkElementRenderer(params Type[] types)
    {
        this.types = types;
    }

    internal override bool Render(UIElement element, PdfRenderContext context)
    {
        var frameworkElement = element as FrameworkElement;
        if (frameworkElement == null)
        {
            return false;
        }

        var hasMatchingType = false;
        var elementType = frameworkElement.GetType();
        foreach (var type in types)
        {
            if (elementType == type || elementType.IsSubclassOf(type))
            {
                hasMatchingType = true;
                break;
            }
        }

        if (!hasMatchingType)
        {
            return false;
        }

        var uiElements = new List<FrameworkElement>();
        for (var i = 0; i < VisualTreeHelper.GetChildrenCount(frameworkElement); i++)
        {
            var child = VisualTreeHelper.GetChild(frameworkElement, i) as FrameworkElement;
            uiElements.Add(child);
        }

        uiElements = uiElements.OrderBy(Panel.GetZIndex).ToList();

        foreach (var child in uiElements)
        {
            context.facade.Render(child, context, false);
        }

        return true;
    }
}